/* 页面加载之前的一些常量 */
const jQuery = window.jQuery,
  echarts = window.echarts;

// gData
const gData = {
  mainHeight: 0,
  commonChk: false,
  voronoiLayerChk: false,
  poorCellList: [],
  balanceList: [],
  allPoorPoints: [],
  commonCellList: [],
  stationList: [],
  fitPoorPoints: [],
  fitAllPoints: [],
  stationPoints: [],
  mapCenter: false,
  polygons: [],
  zoomLevel: 14,
  tab: 'poor',
  // 获取url地址中传递的ecgi
  getEcgi: function () {
    return location.search.match(/[\?*|&*]+ecgi=([^&|\s]*)[&]*|[\s]*/)[1];
  }
};

// ajax请求
const gApi = {};

// map 各种键值对
const gMap = {
  poorFillStyle: {
    2: '#00ff1c', // 冗余
    balance: '#ffcc00', // 负载均衡
    expand: 'red', // 需扩容
    congestion: '#6fe5ec' // 无线信道可优化
  }
};

// chart
const chart = {
  poor: false,
  station: false,
  line: false,
};

// const host = 'http://localhost:8888/volte_capacity-0.0.1-SNAPSHOT';
const host = 'http://10.254.201.218:8888/volte_capacity-0.0.1-SNAPSHOT';

// ajax请求url常量
const requestUrl = {

  // 某时段、某区域（地区）所有的质差小区
  poorCellList: host + '/capacity/poorList',

  balanceList: host + '/capacity/balanceList',

  // 某时段、某区域（地区）所有的一般小区
  commonCellList: host + '/capacity/allList',

  // 某时段、某区域（地区）的各种质差小区数量，画饼图用
  chartPoor: host + '/capacity/poorDistribution',

  // 某市的逻辑基站和小区数量统计
  stationAndCellNum: host + '/capacity/logicBaseByRegion',

  // 某个小区的信息
  cellInfo: host + '/capacity/poorDetail',

  // 某质差小区过去一个月的数据统计 折线图
  cellDataByMonth: host + '/capacity/dataByMonth',

  // 逻辑基站利用率分布，画饼图
  stationUsageList: host + '/capacity/logicBaseDistribution',

  // 逻辑基站列表（绘制泰森多边形）
  stationList: host + '/capacity/logicBase',

  // 逻辑基站信息
  stationInfo: host + '/capacity/logicBaseDetail',

  // 负载均衡小区详情
  loadDetail: host + '/capacity/loadDetail',

  // 预测各逻辑基站需要增加的小区
  addCell: host + '/capacity/allCell',

  // 逻辑基站扩容加站列表（绘制小区）
  addCellList: '../mock/addCellList.json',
};

// storage
const storage = {
  netSelectDate: window.sessionStorage.getItem('netSelectDate'),
  netSelectRegion: window.sessionStorage.getItem('netSelectRegion'),
  netSelectProvince: window.sessionStorage.getItem('netSelectProvince'),
  netSelectCity: window.sessionStorage.getItem('netSelectCity')
};

(function () {
  jQuery(document).ready(function ($) {

    /* 常量 */

    // dom常量
    const dom = {
      $map: $('#map'),
      $mapBox: $('#map_box'),
      $tabBox: $('#tab_box'),
      $rightInfo: $('.right-info'),
      chartPoor: $('#chart_poor')[0],
      chartStation: $('#chart_station')[0],
      chartLine: $('#chart_line')[0],
      $cellNum: $('#cell_num'),
      $cellSelect: $('#cell_select'),

      $domCellName: $('#cell_name'),
      $domPrbUp: $('#prb_up'),
      $domCellType: $('#cell_type'),
      $domCellLevel: $('#cell_level'),
      $domErabNum: $('#erab_num'),
      $domCellPropose: $('#cell_prop'),

      $domDownPrb: $('#down_prb'),
      $domRrc: $('#rrc'),
      $domUpb: $('#upb'),
      $domDownAvg: $('#down_avg'),

      $domUp16qam: $('#up16qam'),
      $domDownPerPrb: $('#downPerPrb'),
      $domCellRation: $('#cell_ration'),

      $cellYear: $('#cell_year'),
      $poorRegionTitle: $('#region_ptitle'),
      $expandRegionTitle: $('#region_etitle'),

      $cnum: $('#cnum'),
      $inNum: $('#inNum'),
      $lock: $('#lock'),
      $outNum: $('#outNum'),
      $six: $('#six'),
      $snum: $('#snum'),
      $three: $('#three'),
      $pooranaInfo: $('#poor_ana_info'),
      $expandplanInfo: $('#expand_plan_info'),

      $threeSingle: $('#three_single'),
      $sixSingle: $('#six_single'),
      $coverType: $('#cover_type'),
      $stationName: $('#station_name'),
      $usage: $('#usage'),
      $networkThickness: $('#network_thickness'),
      $title: $('#title'),
      $propThree: $('#prop_three'),
      $propSix: $('#prop_six'),
      $propMinus: $('#prop_minus'),
      $angleNum: $('#angle_number'),

      $f1: $('#f1'),
      $f2: $('#f2'),
      $d1: $('#d1'),
      $d2: $('#d2'),
      $d3: $('#d3'),

      // 地图dom util
      $commonCellChk: $('#common_cell'),
      $voronoiLayerChk: $('#voronoi_layer')
    };

    // 尺寸
    const size = {
      rightInfoWidth: dom.$rightInfo.width()
    };

    // 地图常量
    const normal = N.getTile('tian', 'normal'),
      nMap = N.map('map', normal), // 封装的leaflet地图方法
      lMap = nMap.getLmap(), // leaflet map 对象实例
      layerSet = {
        cellLayer: L.canvasLayer(),
        dotLayer: L.featureGroup(),
        voronoiLayer: L.d3SvgOverlay(function (sel, proj) {

          // console.log(gData.polygons);

          const upd = sel.selectAll('path').data(gData.polygons);
          let $curPath = undefined;

          // console.log(gData.polygons);

          upd.enter()
            .append('path')
            .attr('opacity', function (d, i) {
              return 0.5;

              // return (Filter.getOpacity(gData.polygons[i]) == 0) ? 'true' : 'false';
            })
            .attr('d', function (d, i) {
              return d3.svg.line().interpolate("basis-closed")(Filter.resample(gData.polygons[i]));
            })
            .attr('stroke-opacity', function (d, i) {
              return gData.stationList[i].ratio >= 15 ? 0.8 : 0.3;
            })
            .attr('stroke-width', function () {
              return 2;
            })
            .attr('stroke', function () {
              return 'rgb(255,102,1)';
            })
            .attr('point', function (d, i) {
              if (d && d.hasOwnProperty('point')) {
                return d.point[0] + ',' + d.point[1];
              }

              return;
            })
            // .attr('style', 'pointer-events:visiblePainted;')
            .style('fill', function (d, i) {
              return Filter.getVoronoiColor(gData.stationList[i].ratio);
            })
            .on('click', function (d, i) {
              const id = gData.stationList[i].logicId;

              // console.log(gData.stationList[i]);

              // console.log(d, i, upd[0][i]);

              // if ($(upd[0][i]).attr('opacity') == 'true') {
              //     return;
              // }

              if ($curPath) {
                $curPath.css('fill', $curPath.attr('data-color'));
              }

              $curPath = $(upd[0][i]);

              $curPath.attr('data-color', $curPath.css('fill'));
              $curPath.css('fill', 'red');

              gApi.logicBaseDetail = $.ajax({
                url: requestUrl.stationInfo,
                method: 'GET',
                dataType: 'json',
                data: {
                  id: id,
                  date: storage.netSelectDate
                }
              });

              gApi.logicBaseDetail
                .done(Response.stationInfo)
                .fail(Response.failConsole);
            });
        })
      },
      // 一般小区选择框
      mapWidgetSet = {
        chkBox: L.control({
          position: 'topleft'
        }),
        voronoiChxBox: L.control({
          position: 'topleft'
        }),
        poorLegend: L.control({
          position: 'bottomleft'
        }),
        addCellLegend: L.control({
          position: 'bottomleft'
        }),
        voronoiLegend: L.control({
          position: 'bottomright'
        }),
      };

    // 打印日志, 主要是ajax错误日志
    const Log = {
      showAjaxError: function (message) {

        // 请求失败
        var msg1 = '响应状态码：' + message.status,
          msg2 = '响应状态描述：' + message.statusText,
          // msg4 = '返回：' + message.responseText.trim(),
          msg3 = 'readyState：' + message.readyState,
          msg5 = '请求' + message.url + '时出错';

        console.log(msg5, msg1, msg2, msg3);
      }
    };

    const AppLogic = {
      setDomValue: function (data) {
        for (let i in data) {
          const key = '$' + i;

          dom[key].text(data[i]);
        }
      }
    };

    const Filter = {
      latLngToLayerPoint: function latLngToLayerPoint(latLngs) {
        const points = [],
          length = latLngs.length;

        for (var i = 0; i < length; i++) {
          const point = lMap.latLngToLayerPoint([latLngs[i][0], latLngs[i][1]]);

          points.push([point.x, point.y]);
        }

        return points;
      },
      getVoronoiColor: function getVoronoiColor(ratio) {
        let color = 'rgba(124,205,124, 1)';

        if (ratio >= 30) {
          color = 'rgba(0,100,0, 1)';
        } else if (25 <= ratio && ratio < 30) {
          color = 'rgba(46,139,87, 1)';
        } else if (15 <= ratio && ratio < 25) {
          color = 'rgba(30,172,30, 1)';
        } else if (5 <= ratio && ratio < 15) {
          color = 'rgba(60,179,113, 1)';
        }

        return color;
      },
      getOpacity: function (polygons) {
        let r = .3;

        console.log(polygons);

        if (!polygons) {
          r = 0;
        } else {
          const isOut = polygons.some(function (item) {
            console.log(item);

            return (Math.max(Math.abs(item[0]), Math.abs(item[1])) > 3000);
          });

          if (isOut) {
            r = 0;
          }
        }

        return r;
      },
      setHiCell: function setHiCell(poorEcgiId, obj, poorList, balanceList) {
        // 高亮小区
        const poorLength = poorList.length,
          balanceLength = balanceList.length;

        const hiId = poorEcgiId.split('-')[0];

        for (let i = 0; i < poorLength; i++) {
          // if (obj.lat === poorList[i].y &&
          //     obj.lng === poorList[i].x) {
          if (hiId === poorList[i].sid) {
            poorList[i].hi = true;

            const cellArr = poorList[i].cl,
              cellLength = cellArr.length;


            for (let j = 0; j < cellLength; j++) {
              if (cellArr[j].cid === poorEcgiId) {
                cellArr[j].hi = true;
              }

              break;
            }

            break;
          }
        }
      },
      resample: function resample(points) {

        // 将d3生成的多边形再优化：返回一个3倍于原来的多边形顶点数量的新多边形
        if (!points) {
          return [];
        }

        const points2 = [],
          n = points.length;

        let i = -1,
          p0 = points[n - 1],
          x0 = p0[0],
          y0 = p0[1],
          p1, x1, y1;

        while (++i < n) {
          p1 = points[i], x1 = p1[0], y1 = p1[1];
          points2.push(
            [(x0 * 2 + x1) / 3, (y0 * 2 + y1) / 3], [(x0 + x1 * 2) / 3, (y0 + y1 * 2) / 3],
            p1
          );
          p0 = p1, x0 = x1, y0 = y1;
        }

        return points2;
      }
    };

    const Response = {
      failConsole: function (jqxhr) {

        // 请求失败
        Log.showAjaxError({
          status: jqxhr.status,
          statusText: jqxhr.statusText,
          responseText: jqxhr.responseText,
          readyState: jqxhr.readyState,
          url: this.url
        });
      },
      addCell: function (data) {
        console.log('预测各逻辑基站需要增加的小区', data);

        // 检查数据
        if (data.code === 1) {
          console.log('后台未返回各逻辑基站需要增加的小区');
        } else if (data.code === 0 && data.data) {
          const sData = (data.data === undefined) ? [] : data.data,
            length = sData.length;

          if (length === 0) {
            console.log('后台返回各逻辑基站需要增加的小区长度为0');
          } else {
            const arr = [];
            let i = length - 1;

            while (i >= 0) {
              arr.push([sData[i].x, sData[i].y]);
              i--;
            }

            layerSet.cellLayer.delegate(window).removeFrom(lMap);
            lMap.panTo(N.Util.getCenter(arr));
            layerSet.cellLayer.delegate(window).addTo(lMap);

            gData.addCell = sData;
          }
        }
      },
      stationInfo: function (data) {
        console.log('逻辑基站详细信息：', data);

        if (data.code === 1) {
          console.log('后台未返回逻辑基站信息');
        } else if (data.code === 0 && data.data) {
          var sData = data.data;

          const obj = {
            enode: {
              enodebname: '', // 名称
              covertype: '', // 类型,
              networkThickness: '', // 基站厚度
              mergedfrenums: '', // 包含小区数
              f1frequencenums: '',
              f2frequencenums: '',
              d1frequencenums: '',
              d2frequencenums: '',
              d3frequencenums: '',
              e1frequencenums: '', // 室内
              e2frequencenums: '', // 室内
              e3frequencenums: '' // 室内
            },
            propose: {
              usage: '', // 基站利用率,
              title: '', // 建议标题
              three: '', // 3个月建议
              six: '', // 6个月建议,
              minus: '', // 减容建议
              threeNum: '', // 3个月增加载频数
              sixNum: '', // 6个月增加载频数,
            }
          };

          for (let i in obj.enode) {
            if (sData.enode[i] !== undefined && sData.enode[i] !== null) {
              obj.enode[i] = sData.enode[i];
            } else {
              obj.enode[i] = '';
            }
          }

          for (let i in obj.propose) {
            if (sData.propose[i] !== undefined && sData.propose[i] !== null) {
              obj.propose[i] = sData.propose[i];
            } else {
              obj.propose[i] = '';
            }
          }

          const usageText = isNaN(parseFloat(obj.propose.usage)) ?
            '' : obj.propose.usage.toFixed(2) + '%',
            proposeThree = obj.propose.three === '' ? '' :
            '3个月建议：' + obj.propose.three,
            proposeSix = obj.propose.six === '' ? '' :
            '6个月建议：' + obj.propose.six;



          dom.$stationName.text(obj.enode.enodebname);
          dom.$coverType.text(obj.enode.covertype);
          dom.$networkThickness.text(obj.enode.networkThickness);
          dom.$angleNum.text(obj.enode.mergedfrenums);

          dom.$usage.text(usageText);
          dom.$title.text(obj.propose.title);
          dom.$threeSingle.text(obj.propose.threeNum);
          dom.$sixSingle.text(obj.propose.sixNum);

          dom.$propThree.text(proposeThree);
          dom.$propSix.text(proposeSix);
          dom.$propMinus.text(obj.propose.minus);

          dom.$f1.text(obj.enode.f1frequencenums);
          dom.$f2.text(obj.enode.f2frequencenums);
          dom.$d1.text(obj.enode.d1frequencenums);
          dom.$d2.text(obj.enode.d2frequencenums);
          dom.$d3.text(obj.enode.d3frequencenums);
        } else {
          console.log('后台未返回逻辑基站信息');

          dom.$stationName.text('');
          dom.$coverType.text('');
          dom.$networkThickness.text('');
          dom.$angleNum.text('');

          dom.$usage.text('');
          dom.$title.text('');
          dom.$threeSingle.text('');
          dom.$sixSingle.text('');
          dom.$propThree.text('');
          dom.$propSix.text('');
          dom.$propMinus.text('');

          dom.$f1.text('');
          dom.$f2.text('');
          dom.$d1.text('');
          dom.$d2.text('');
          dom.$d3.text('');
        }
      },
      stationAndCellNum: function (data) {
        console.log('逻辑基站和小区数统计', data);

        if (data.code === 1) {
          console.log('后台未返回数据');
        } else if (data.code === 0 && data.data) {
          const sData = data.data;

          if (!N.Util.isObject(sData)) {
            console.log('后台返回数据格式不正确');
          } else {
            const obj = {
              cnum: '',
              inNum: '',
              lock: '',
              outNum: '',
              six: '',
              snum: '',
              three: ''
            };

            for (let i in obj) {
              if (sData[i] !== undefined && sData[i] !== null) {
                obj[i] = sData[i];
              }
            }

            obj.cnum = obj.inNum + obj.outNum;

            console.log(obj);

            AppLogic.setDomValue(obj);
          }
        } else {
          console.log('后台返回数据格式不正确');
        }
      },
      stationList: function (data) {
        console.log('逻辑基站列表:', data);

        if (data.code === 1) {
          console.log('后台未返回数据');
        } else if (data.code === 0 && data.data) {
          const sData = data.data;

          if (!N.Util.isArray(sData)) {
            console.log('后台返回数据格式不正确');
          } else {
            const length = sData.length;

            if (length === 0) {
              console.log('后台返回逻辑基站列表长度为0');
            } else {
              const arr = [];

              gData.stationList = sData;

              // console.log(sData);

              for (let i = 0; i < length; i++) {
                if (sData[i].covertype === '室外') {
                  const station = L.circleMarker([sData[i].latitude, sData[i].longitude], {
                    radius: 1
                  });

                  station.id = sData[i].logicId;
                  station.covertype = sData[i].covertype;
                  station.lat = sData[i].latitude;
                  station.lng = sData[i].longitude;

                  layerSet.dotLayer
                    .addLayer(station);
                } else {
                  const station = L.circleMarker([sData[i].latitude, sData[i].longitude], {
                    radius: 1,
                    color: 'red',
                    fill: true
                  });

                  station.id = sData[i].logicId;

                  layerSet.dotLayer
                    .addLayer(station);
                }
              }

              layerSet.dotLayer.addTo(lMap);
            }
          }
        } else {
          console.log('后台返回数据格式不正确');
        }
      },
      voronoiList: function (data) {
        console.log('逻辑基站列表:', data);

        if (data.code === 0 && data.data) {
          const sData = data.data;

          if (!N.Util.isArray(sData)) {
            console.log('后台返回数据格式不正确');
          } else {
            const length = sData.length;

            if (length === 0) {
              console.log('后台返回逻辑基站列表长度为0');
            } else {
              const points = [],
                ssData = [];

              sData.forEach(function (d) {
                if (d.longitude && d.latitude && d.covertype === '室外') {
                  points.push([d.latitude, d.longitude]);
                  ssData.push(d);
                }
              });

              gData.stationPoints = points;
              gData.stationList = ssData;

              gData.polygons = d3.geom.voronoi(Filter.latLngToLayerPoint(points));

              // lMap.panTo(gData.mapCenter);
            }
          }
        } else {
          console.log('后台返回数据格式不正确');
        }
      },
      poorCellList: function (data) {
        console.log('质差小区列表:', data);

        // 检查数据
        if (data.code === 1) {
          console.log('后台未返回质差小区列表数据');
        } else if (data.code === 0 && data.data) {
          const sData = (data.data === undefined) ? [] : data.data,
            length = sData.length;

          if (length === 0) {
            console.log('后台返回质差小区列表长度为0');
          } else {
            gData.poorCellList = sData;

            const arr = [];

            // 处理数据，将所有小区的经纬度提取出来构造数组，用于确定地图边界
            for (let i = length - 1; i >= 0; i--) {
              arr.push([sData[i].y, sData[i].x]);
            }

            gData.fitPoorPoints = arr;

            // layerSet.cellLayer.delegate(window).removeFrom(lMap);
            // layerSet.cellLayer.delegate(window).addTo(lMap);

            lMap.fitBounds(arr.concat(gData.fitPoorPoints));

            gData.zoomLevel = lMap.getZoom();

            const poorEcgiId = gData.getEcgi();

            if (poorEcgiId !== undefined) {
              // 请求某质差小区的详细信息
              if (!gApi.passCellInfo) {
                gApi.passCellInfo = $.ajax({
                  url: requestUrl.cellInfo,
                  method: 'GET',
                  dataType: 'json',
                  data: {
                    id: poorEcgiId,
                    date: storage.netSelectDate
                  }
                });
              }

              gApi.passCellInfo
                .done(function (data) {
                  console.log('小区详细信息：', data);

                  // 检查数据
                  if (data.code === 1) {
                    console.log('后台未返回一般小区信息');
                  } else if (data.code === 0 && data.data) {
                    var sData = data.data,
                      obj = {
                        cellLevel: '',
                        cellType: '',
                        erabNum: '',
                        name: '',
                        prbUp: '',
                        cellPropose: '',
                        lat: '',
                        lng: '',
                        downPrb: '',
                        rrc: '',
                        upB: '',
                        downAvg: '',
                        downPerPrb: '', // 下行每PRB平均吞吐量
                        up16qam: '', // 上行16QAM及以上编码比例
                        cellRation: '' // 小区自忙时的网络利用率
                      };

                    if (N.Util.isObject(sData)) {
                      for (var i in obj) {
                        if (sData[i] !== undefined && sData[i] !== null) {
                          obj[i] = sData[i];
                        } else {
                          obj[i] = '';
                        }
                      }

                      const downPrb = obj.downPrb === '' ?
                        '' : obj.downPrb.toFixed(2) + '%',
                        prbUp = obj.prbUp === '' ?
                        '' : obj.prbUp.toFixed(2) + '%',
                        rrc = obj.rrc === '' ? '' :
                        Math.floor(obj.rrc.toFixed(2)),
                        upB = obj.upB === '' ? '' :
                        obj.upB.toFixed(2),
                        downAvg = obj.downAvg === '' ? '' :
                        Math.floor(obj.downAvg.toFixed(2)),
                        up16qam = obj.up16qam === '' ? '' :
                        obj.up16qam.toFixed(2) + '%',
                        downPerPrb = obj.downPerPrb === '' ? '' :
                        obj.downPerPrb.toFixed(2),
                        cellRation = obj.cellRation === '' ?
                        '' : obj.cellRation.toFixed(2) + '%',
                        erabNum = obj.erabNum === '' ?
                        '' : Math.floor(obj.erabNum.toFixed(2));

                      dom.$domCellName.text(obj.name);
                      dom.$domPrbUp.text(prbUp);
                      dom.$domCellType.text(obj.cellType);
                      dom.$domCellLevel.text(obj.cellLevel);
                      dom.$domErabNum.text(erabNum);
                      dom.$domCellPropose.text(obj.cellPropose);

                      dom.$domDownPrb.text(downPrb);
                      dom.$domRrc.text(rrc);
                      dom.$domUpb.text(upB);
                      dom.$domDownAvg.text(downAvg);

                      dom.$domUp16qam.text(up16qam);
                      dom.$domDownPerPrb.text(downPerPrb);

                      dom.$domCellRation.text(cellRation);

                      // 设置地图中心
                      lMap.setView([obj.lat, obj.lng], 17);

                      Filter.setHiCell(poorEcgiId, obj, gData.poorCellList, gData.balanceList);

                      gData.zoomLevel = lMap.getZoom();

                      lMap.panTo([obj.lat, obj.lng]);

                      layerSet.cellLayer.delegate(window).removeFrom(lMap);
                      layerSet.cellLayer.delegate(window).addTo(lMap);
                    } else if (sData === null) {
                      dom.$domCellName.text(obj.name);
                      dom.$domPrbUp.text(obj.prbUp);
                      dom.$domCellType.text(obj.cellType);
                      dom.$domCellLevel.text(obj.cellLevel);
                      dom.$domErabNum.text(obj.erabNum);
                      dom.$domCellPropose.text(obj.cellPropose);

                      dom.$domDownPrb.text(obj.downPrb);
                      dom.$domRrc.text(obj.rrc);
                      dom.$domUpb.text(obj.upB);
                      dom.$domDownAvg.text(obj.downAvg);

                      dom.$domUp16qam.text(obj.up16qam);
                      dom.$domDownPerPrb.text(obj.downPerPrb);
                      dom.$domCellRation.text(obj.cellRation);
                    }
                  } else if (data.code === 0 && !(data.data)) {
                    var emptyText = '';

                    dom.$domCellName.text(emptyText);
                    dom.$domPrbUp.text(emptyText);
                    dom.$domCellType.text(emptyText);
                    dom.$domCellLevel.text(emptyText);
                    dom.$domErabNum.text(emptyText);
                    dom.$domCellPropose.text(emptyText);

                    dom.$domDownPrb.text(emptyText);
                    dom.$domRrc.text(emptyText);
                    dom.$domUpb.text(emptyText);
                    dom.$domDownAvg.text(emptyText);

                    dom.$domUp16qam.text(emptyText);
                    dom.$domDownPerPrb.text(emptyText);
                    dom.$domCellRation.text(emptyText);
                  }
                })
                .fail(Response.failConsole);

              // 请求某质差小区的曲线图
              if (!gApi.passCellChart) {
                gApi.passCellChart = $.ajax({
                  url: requestUrl.cellDataByMonth,
                  method: 'GET',
                  dataType: 'json',
                  data: {
                    id: poorEcgiId,
                    date: storage.netSelectDate,
                    type: dom.$cellSelect.val()
                  }
                });
              }

              gApi.passCellChart
                .done(function (data) {
                  console.log('小区曲线数据', data);

                  // 检查数据
                  if (data.code === 1) {
                    console.log('后台未返回一般小区信息');
                  } else if (data.code === 0 && data.data) {
                    var sData = data.data;

                    if (!sData.x || !sData.s || !N.Util.isArray(sData.x) ||
                      !N.Util.isArray(sData.s) ||
                      sData.x.length !== sData.s.length) {
                      console.log('后台未返回合法的质差小区统计数据');
                    } else {
                      var xData = sData.x,
                        seriesData = sData.s,
                        seriesDataLength = seriesData.length,
                        newSeriesData = [];

                      if (xData[0] && xData[0].indexOf('-') !== -1) {
                        dom.$cellYear.text(xData[0].split('-')[0] + '年');
                      }

                      for (var i = 0; i < seriesDataLength; i++) {
                        newSeriesData.push(seriesData[i].toFixed(2));
                      }

                      var option = {
                        color: ['#0f0'],
                        grid: {
                          height: '55%',
                          top: 40
                        },
                        backgroundColor: '#fff',
                        tooltip: {
                          trigger: 'axis'
                        },
                        xAxis: {
                          type: 'category',
                          boundaryGap: false,
                          data: xData
                        },
                        axisLabel: {
                          formatter: function (value, index) {
                            if (value !== undefined && value.indexOf('-') !== -1) {
                              var arr = value.split('-');

                              arr.shift();

                              return arr.join("\n");
                            } else {
                              return value;
                            }
                          },
                          interval: 0
                        },
                        yAxis: {
                          type: 'value',
                          axisLabel: {
                            formatter: '{value}'
                          }
                        },
                        series: [{
                          type: 'line',
                          smooth: true,
                          data: newSeriesData,
                          markPoint: {
                            data: [{
                              type: 'max',
                              name: '最大值'
                            }]
                          },
                          areaStyle: {
                            normal: {
                              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                                offset: 0,
                                color: 'rgb(168, 255, 151)'
                              }, {
                                offset: 1,
                                color: 'rgb(244, 255, 241)'
                              }])
                            }
                          }
                        }]
                      };

                      chart.line.setOption(option, true);
                    }
                  }
                })
                .fail(Response.failConsole);
            } else {
              layerSet.cellLayer.delegate(window).removeFrom(lMap);
              layerSet.cellLayer.delegate(window).addTo(lMap);
            }
          }
        }
      },
      commonCellList: function (data) {
        console.log('一般小区列表:', data);

        // 检查数据
        if (data.code === 1) {
          console.log('后台未返回一般小区列表数据');
        } else if (data.code === 0) {
          const sData = (data.data === undefined) ? [] : data.data,
            length = sData.length;

          if (length === 0) {
            console.log('后台返回一般小区列表长度为0');
          } else {
            gData.commonCellList = sData;

            lMap.panTo(gData.mapCenter);
          }
        }
      },
      chartPoor: function (data) {
        // console.log('某时段、某区域质差小区分类统计', data);

        // 检查数据
        if (data.code === 1) {
          console.log('后台未返回质差小区分类统计数据');
        } else if (data.code === 0) {
          const sData = (data.data === undefined) ? {} : data.data,
            obj = {
              // '其他小区': 0,
              '容量冗余小区': 0,
              '容量拥塞-无限信道优化可解决小区': 0,
              '容量拥塞-负载均衡可解决小区': 0,
              '容量拥塞-需扩容解决小区': 0
            };

          if (!N.Util.isObject(sData)) {
            console.log('后台返回质差小区分类统计数据格式不正确');
          } else {
            for (let i in obj) {
              if (sData[i]) {
                obj[i] = sData[i];
              }
            }

            const seriesData = [],
              legendData = [];
            let sum = 0;

            for (let i in obj) {
              seriesData.push({
                value: obj[i],
                name: i
              });

              legendData.push(i);
              sum += obj[i];
            }

            dom.$cellNum.text(sum === 0 ? '' : sum);
            seriesData.reverse();
            legendData.reverse();

            // 绘制图表：饼图
            const option = {
              color: [
                gMap.poorFillStyle['expand'],
                gMap.poorFillStyle['balance'],
                gMap.poorFillStyle['congestion'],
                gMap.poorFillStyle[2]
              ],
              title: {
                text: '',
                subtext: '',
              },
              tooltip: {
                show: true,
                trigger: 'item',
                formatter: "{a} <br/>{b} : {c} ({d}%)"
              },
              legend: {
                orient: 'vertical',
                // left: 'right',
                data: legendData,
                bottom: 20,
                right: 30,
                itemGap: 10
              },
              series: [{
                name: '类型',
                type: 'pie',
                radius: '55%',
                center: ['26%', '45%'],
                data: seriesData,
                label: {
                  normal: {
                    show: false
                  }
                },
                itemStyle: {
                  emphasis: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                  }
                }
              }]
            };

            chart.poor.setOption(option);
          }
        }
      },
      chartStation: function (data) {
        // console.log('某时段、某区域逻辑基站利用率统计', data);

        // 检查数据
        if (data.code === 1) {
          console.log('后台未返回逻辑基站利用率统计数据');
        } else if (data.code === 0) {
          const sData = (data.data === undefined) ? {} : data.data;

          if (!sData.x || !sData.s) {
            console.log('后台未返回合法的逻辑基站利用率统计数据');
          } else {
            if (!N.Util.isArray(sData.x) || !N.Util.isArray(sData.s)) {
              console.log('返回的坐标轴数据不是数组');
            } else if (sData.x.length !== sData.s.length) {
              console.log('两坐标轴数值不是一一对应的关系');
            } else {

              const seriesData = [],
                legendData = [],
                length = sData.x.length;

              for (let i = length - 1; i >= 0; i--) {

                let name = '0-5%';

                switch (sData.x[i]) {
                  case 'a':
                    name = '0-5%';

                    break;
                  case 'b':
                    name = '5-15%';

                    break;
                  case 'c':
                    name = '15-25%';

                    break;
                  case 'd':
                    name = '25-30%';

                    break;
                  case 'e':
                    name = '>30%';

                    break;
                  default:
                }

                legendData.push(name);

                seriesData.push({
                  value: sData.s[i],
                  name: name
                });
              }

              // seriesData.reverse();
              // legendData.reverse();

              const colors = ['rgba(124,205,124, 0.6)', 'rgba(60,179,113, 0.6)', 'rgba(30,172,30, 0.6)', 'rgba(46,139,87, 0.6)', 'rgba(0,100,0,0.6)'].reverse();

              // 绘制图表：饼图
              const option = {
                // color: ['#51bde4', '#7bd4f6', '#8ee1e9', '#b2edd9', '#c4f8d1'],
                color: colors,
                title: {
                  text: '',
                  subtext: '',
                },
                tooltip: {
                  trigger: 'item',
                  formatter: "{a} <br/>{b} : {c} ({d}%)"
                },
                legend: {
                  orient: 'vertical',
                  // left: 'right',
                  data: legendData,
                  top: 20,
                  right: 100,
                  itemGap: 10
                },
                series: [{
                  name: '利用率',
                  type: 'pie',
                  radius: '70%',
                  center: ['30%', '50%'],
                  data: seriesData,
                  label: {
                    normal: {
                      show: false
                    }
                  },
                  itemStyle: {
                    emphasis: {
                      shadowBlur: 10,
                      shadowOffsetX: 0,
                      shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                  }
                }]
              };

              chart.station.setOption(option);
            }
          }
        }
      }
    };

    // 添加地图自定义dom控件时触发事件的回调函数
    mapWidgetSet.chkBox.onAdd = function (map) {
      var div = L.DomUtil.create('div', 'map-chkbox');

      div.innerHTML = '<input class="common-chkbox" type="checkbox" id="common_cell">' +
        '<label class="common-label" for="common_cell">一般小区</label>'

      return div;
    };

    mapWidgetSet.voronoiChxBox.onAdd = function (map) {
      var div = L.DomUtil.create('div', 'map-voronoichkbox');

      div.innerHTML = '<input class="voronoi-chkbox" type="checkbox" id="voronoi_layer">' +
        '<label class="common-label" for="voronoi_layer">逻辑基站</label>'

      return div;
    };

    mapWidgetSet.poorLegend.onAdd = function (map) {
      const div = L.DomUtil.create('div', 'map-plegend'),
        colors = [
          [gMap.poorFillStyle['expand'], '需扩容小区'],
          [gMap.poorFillStyle['balance'], '可负载均衡小区'],
          [gMap.poorFillStyle['congestion'], '可无线信道优化小区'],
          [gMap.poorFillStyle[2], '容量冗余小区']
        ];

      div.innerHTML = N.Util.getColorLegend(colors);

      return div;
    };

    mapWidgetSet.addCellLegend.onAdd = function (map) {
      const div = L.DomUtil.create('div', 'map-aclegend'),
        colors = [
          ['rgb(107, 57, 6)', 'D1'],
          ['rgb(152, 36, 207)', 'D2'],
          ['rgb(235, 97, 0)', 'D3'],
          ['yellow', 'E1'],
          ['green', 'E2'],
          ['blue', 'E3'],
          ['rgb(234, 96, 155)', 'F1'],
          ['rgb(254, 12, 63)', 'F2'],
        ];

      div.innerHTML = N.Util.getColorLegend(colors);

      return div;
    };

    mapWidgetSet.voronoiLegend.onAdd = function (map) {
      const div = L.DomUtil.create('div', 'map-vlegend'),
        colors = [
          ['rgba(0,100,0,0.6)', '>30%'],
          ['rgba(46,139,87, 0.6)', '25-30%'],
          ['rgba(30,172,30, 0.6)', '15-25%'],
          ['rgba(60,179,113, 0.6)', '5-15%'],
          ['rgba(124,205,124, 0.6)', '0-5%']
        ];

      // colors = [
      //     ['#51bde4', '>30%'],
      //     ['#7bd4f6', '25-30%'],
      //     ['#8ee1e9', '15-25%'],
      //     ['#b2edd9', '5-15%'],
      //     ['#c4f8d1', '0-5%']
      // ];

      div.innerHTML = N.Util.getColorLegend(colors);

      return div;
    };

    const Size = {
      setMainHeight: function () {
        const mainHeight = window.innerHeight - $('.headbg').height() - $('.top-bar').height() - 40;

        // 设置.main-content 外层容器
        $('.main-content').css('height', mainHeight);

        // 设置地图高度
        $('#map').css('height', mainHeight);

        // 设置右侧上部图表容器的高度 right-info__phead
        $('.right-info__phead').css('height', mainHeight * 0.3);
        $('#chart_poor').css('height', mainHeight * 0.3 * 0.8);

        $('.right-info__pbody').css('height', mainHeight * 0.5);


        $('.right-info__pfoot').css('height', mainHeight * 0.2);
        $('#chart_line').css('height', mainHeight * 0.2);

        return mainHeight;
      }
    };



    /* 业务逻辑 */

    // 设置.main-content高度
    // const mainHeight = Size.setMainHeight();

    // gData.mainHeight = mainHeight;

    // console.log(mainHeight);



    // 设置右侧顶部标题
    // dom.$poorRegionTitle.text(sessionStorage.getItem('netSelectRegion'));
    // dom.$expandRegionTitle.text(sessionStorage.getItem('netSelectRegion'));

    dom.$poorRegionTitle.text(sessionStorage.getItem('netSelectCity'));
    dom.$expandRegionTitle.text(sessionStorage.getItem('netSelectCity'));

    // 设置右侧图表的宽度
    $(dom.chartStation).css('width', size.rightInfoWidth);

    chart.poor = echarts.init(dom.chartPoor);
    chart.station = echarts.init(dom.chartStation);
    chart.line = echarts.init(dom.chartLine);

    // 设置地图容器尺寸
    dom.$map.css({
      width: dom.$mapBox.width(),
      height: dom.$mapBox.height()
    });

    // 地图初始化: 设置组件和图层
    mapWidgetSet.chkBox.addTo(lMap);
    mapWidgetSet.voronoiChxBox.addTo(lMap);
    $('.map-voronoichkbox').hide();

    nMap.addZoom().addCoord().addScale();
    const layerControl = nMap.setLayers({
      '地图': normal,
      '影像': N.getTile('tian', 'satellite'),
      '地形': N.getTile('tian', 'terrain')
    });
    mapWidgetSet.poorLegend.addTo(lMap);

    lMap.setView({
      lng: 114.5024,
      lat: 38.0409
    }, 4);


    // 请求容量拥塞和冗余小区  如果页面传递了ecgi，会请求这个小区的detail信息
    if (!gApi.poorCellList) {
      gApi.poorCellList = $.ajax({
        url: requestUrl.poorCellList,
        method: 'GET',
        dataType: 'json',
        data: {
          date: storage.netSelectDate,
          province: storage.netSelectProvince,
          city: storage.netSelectCity
        }
      });
    }
    gApi.poorCellList
      .done(Response.poorCellList)
      .fail(Response.failConsole);

    // 质差小区图表
    if (!gApi.chartPoor) {
      gApi.chartPoor = $.ajax({
        url: requestUrl.chartPoor,
        method: 'GET',
        dataType: 'json',
        data: {
          date: storage.netSelectDate,
          province: storage.netSelectProvince,
          city: storage.netSelectCity
        }
      });
    }
    gApi.chartPoor
      .done(Response.chartPoor)
      .fail(Response.failConsole);

    // 基站利用率图表
    if (!gApi.stationUsageList) {
      gApi.stationUsageList = $.ajax({
        url: requestUrl.stationUsageList,
        method: 'GET',
        dataType: 'json',
        data: {
          date: storage.netSelectDate,
          province: storage.netSelectProvince,
          city: storage.netSelectCity
        }
      });
    }

    gApi.stationUsageList
      .done(Response.chartStation)
      .fail(Response.failConsole);

    // 逻辑基站和小区数量统计
    if (!gApi.stationAndCellNum) {
      gApi.stationAndCellNum = $.ajax({
        url: requestUrl.stationAndCellNum,
        method: 'GET',
        dataType: 'json',
        data: {
          date: storage.netSelectDate,
          province: storage.netSelectProvince,
          city: storage.netSelectCity
        }
      });
    }

    gApi.stationAndCellNum
      .done(Response.stationAndCellNum)
      .fail(Response.failConsole);


    /* 事件 */

    // echarts图表大小重新渲染
    // $(window).on('resize', function() {

    //     chart.poor.resize();
    //     chart.station.resize();
    //     chart.line.resize();
    // });

    // tab切换
    dom.$tabBox.on('click', '.top-bar__tab', function (e) {
      const $target = $(e.target),
        tabId = $target[0].id;

      $target.addClass('active');
      $target.siblings('.top-bar__tab').removeClass('active');

      gData.mapCenter = lMap.getCenter();

      if (tabId === 'poor_ana') {
        dom.$pooranaInfo.addClass('active');
        dom.$expandplanInfo.removeClass('active');
      } else {
        dom.$pooranaInfo.removeClass('active');
        dom.$expandplanInfo.addClass('active');
      }

      if (tabId === 'expand_plan') {
        gData.tab = 'expand';

        // 切换到扩减容规划时
        layerSet.cellLayer.delegate(window).removeFrom(lMap);
        layerSet.cellLayer.delegate(window).addTo(lMap);

        // layerSet.dotLayer.addTo(lMap);

        if (gData.voronoiLayerChk === true) {
          layerSet.voronoiLayer.addTo(lMap);
        }


        // layerControl.removeLayer(layerSet.voronoiLayer);
        // layerControl.addOverlay(layerSet.voronoiLayer, '逻辑基站');

        // mapWidgetSet.chkBox.remove();
        $('.map-chkbox').hide();
        $('.map-voronoichkbox').show();
        mapWidgetSet.poorLegend.remove();
        mapWidgetSet.addCellLegend.addTo(lMap);
        mapWidgetSet.voronoiLegend.addTo(lMap);

        // 逻辑基站列表
        if (!gApi.voronoiList) {
          gApi.voronoiList = $.ajax({
            url: requestUrl.stationList,
            method: 'GET',
            dataType: 'json',
            data: {
              date: storage.netSelectDate,
              province: storage.netSelectProvince,
              city: storage.netSelectCity
            }
          });
        }

        // if (!gApi.stationList) {
        //     gApi.stationList = $.ajax({
        //         url: requestUrl.stationList,
        //         method: 'GET',
        //         dataType: 'json',
        //         data: {
        //             date: storage.netSelectDate,
        //             province: storage.netSelectProvince,
        //             city: storage.netSelectCity
        //         }
        //     });
        // }

        // gApi.stationList
        //     .done(Response.stationList)
        //     .fail(Response.failConsole);

        gApi.voronoiList
          .done(Response.voronoiList)
          .fail(Response.failConsole);


        // 请求容量拥塞和冗余小区
        if (!gApi.addCell) {
          gApi.addCell = $.ajax({
            url: requestUrl.addCell,
            method: 'GET',
            dataType: 'json',
            data: {
              date: storage.netSelectDate,
              province: storage.netSelectProvince,
              city: storage.netSelectCity
            }
          });
        }

        gApi.addCell
          .done(Response.addCell)
          .fail(Response.failConsole);

      } else if (tabId === 'poor_ana') {
        gData.tab = 'poor';

        // 切换到质差小区分析
        layerSet.cellLayer.delegate(window).removeFrom(lMap);
        layerSet.cellLayer.delegate(window).addTo(lMap);
        layerSet.voronoiLayer.removeFrom(lMap);
        // layerSet.dotLayer.removeFrom(lMap);

        // layerControl.removeLayer(layerSet.voronoiLayer);

        $('.map-chkbox').show();
        $('.map-voronoichkbox').hide();
        // mapWidgetSet.chkBox.addTo(lMap);
        mapWidgetSet.poorLegend.addTo(lMap);
        mapWidgetSet.addCellLegend.remove();
        mapWidgetSet.voronoiLegend.remove();

        lMap.panTo(gData.mapCenter);
      }
    });

    // 自定义地图控件: 一般小区
    $('#common_cell').on('change', function (e) {
      // console.log(e, e.target, e.target.checked);

      if (e.target.checked === true) {
        gData.commonChk = true;

        if (!gApi.commonCellList) {
          gApi.commonCellList = $.ajax({
            url: requestUrl.commonCellList,
            method: 'GET',
            dataType: 'json',
            data: {
              date: storage.netSelectDate,
              province: storage.netSelectProvince,
              city: storage.netSelectCity
            }
          });
        }

        gApi.commonCellList
          .done(Response.commonCellList)
          .fail(Response.failConsole);
      } else {
        layerSet.cellLayer.delegate(window).removeFrom(lMap);
        layerSet.cellLayer.delegate(window).addTo(lMap);
        // lMap.fitBounds(gData.fitPoorPoints);
        lMap.panTo(gData.mapCenter);
        gData.commonChk = false;
      }
    });


    // 自定义地图控件: 逻辑基站
    $('#voronoi_layer').on('change', function (e) {
      if (e.target.checked === true) {
        gData.voronoiLayerChk = true;
        if (!lMap.hasLayer(layerSet.voronoiLayer)) {
          gData.polygons = d3.geom.voronoi(Filter.latLngToLayerPoint(gData.stationPoints));
          layerSet.voronoiLayer.removeFrom(lMap);
          layerSet.voronoiLayer.addTo(lMap);
        }
      } else {
        gData.voronoiLayerChk = false;
        layerSet.voronoiLayer.removeFrom(lMap);
      }
    });

    // 刷新事件
    window.onbeforeunload = function (e) {
      window.sessionStorage.removeItem('clickCellId');
    };

    // 拖动事件
    lMap.on('dragstart', function (e) {
      if (lMap.hasLayer(layerSet.cellLayer)) {
        layerSet.cellLayer.delegate(window).removeFrom(lMap);
      }
    });

    // 拖动结束事件
    lMap.on('dragend', function (e) {
      gData.mapCenter = lMap.getCenter();

      if (!lMap.hasLayer(layerSet.cellLayer)) {
        layerSet.cellLayer.delegate(window).addTo(lMap);
      }
    });

    lMap.on('zoomstart', function () {
      if (gData.tab === 'expand') {
        layerSet.voronoiLayer.removeFrom(lMap);
      }
    });

    // 缩放结束事件
    lMap.on('zoomend', function (e) {
      gData.mapCenter = lMap.getCenter();

      if (gData.tab === 'expand' && gData.voronoiLayerChk === true) {
        gData.polygons = d3.geom.voronoi(Filter.latLngToLayerPoint(gData.stationPoints));

        // console.log(gData.stationPoints, Filter.latLngToLayerPoint(gData.stationPoints), gData.polygons);

        layerSet.voronoiLayer.removeFrom(lMap);
        layerSet.voronoiLayer.addTo(lMap);
      }
    });

    // layerSet.dotLayer.on('click', function(e) {
    //     console.log(e);
    // });


    dom.$cellSelect.on('change', function (e) {
      const type = dom.$cellSelect.val(),
        cid = sessionStorage.getItem('clickCellId') || gData.getEcgi(),
        date = storage.netSelectDate;


      if (cid !== null) {
        $.ajax({
          url: requestUrl.cellDataByMonth,
          method: 'GET',
          dataType: 'json',
          data: {
            id: cid,
            date: date,
            type: type
          },
          success: function (data) {
            console.log('小区曲线数据', data);

            // 检查数据
            if (data.code === 1) {
              console.log('后台未返回一般小区信息');
            } else if (data.code === 0 && data.data) {
              var sData = data.data;

              if (!sData.x || !sData.s || !N.Util.isArray(sData.x) ||
                !N.Util.isArray(sData.s) ||
                sData.x.length !== sData.s.length) {
                console.log('后台未返回合法的质差小区统计数据');
              } else {
                var xData = sData.x,
                  seriesData = sData.s,
                  seriesDataLength = seriesData.length,
                  newSeriesData = [];

                if (xData[0] && xData[0].indexOf('-') !== -1) {
                  dom.$cellYear.text(xData[0].split('-')[0] + '年');
                }

                for (var i = 0; i < seriesDataLength; i++) {
                  newSeriesData.push(seriesData[i].toFixed(2));
                }

                var option = {
                  color: ['#0f0'],
                  backgroundColor: '#fff',
                  tooltip: {
                    trigger: 'axis'
                  },
                  grid: {
                    height: '55%',
                    top: 40
                  },
                  xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: xData
                  },
                  axisLabel: {
                    formatter: function (value, index) {
                      if (value !== undefined && value.indexOf('-') !== -1) {
                        var arr = value.split('-');

                        arr.shift();

                        return arr.join("\n");
                      } else {
                        return value;
                      }
                    },
                    interval: 0
                  },
                  yAxis: {
                    type: 'value',
                    axisLabel: {
                      formatter: '{value}'
                    }
                  },
                  series: [{
                    type: 'line',
                    smooth: true,
                    data: newSeriesData,
                    markPoint: {
                      data: [{
                        type: 'max',
                        name: '最大值'
                      }]
                    },
                    areaStyle: {
                      normal: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                          offset: 0,
                          color: 'rgb(168, 255, 151)'
                        }, {
                          offset: 1,
                          color: 'rgb(244, 255, 241)'
                        }])
                      }
                    }
                  }]
                };

                chart.line.setOption(option, true);
              }
            }
          },
          error: function (jqxhr) {
            var errMsg1 = '请求' + this.url + '时出错',
              errMsg2 = '服务器返回http状态码:' + jqxhr.status,
              errMsg3 = '服务器返回内容:' + (jqxhr.responseText ? jqxhr.responseText.trim() : '服务器未响应');

            console.log(errMsg1, errMsg2, errMsg3);
          }
        });
      }
    });
  });
})();



/**
 * gLayers.Leaflet插件的回调函数
 *
 * @param info
 * @return
 */
var onDrawLayer = function (info) {
  'use strict';

  // 地图和createjs的stage
  const map = info.layer._map,
    stage = new createjs.Stage(info.canvas);

  stage.enableMouseOver(20);
  stage.clear();

  // 基站和扇区数据
  const allPoorPoints = gData.poorCellList,
    allPoorLength = allPoorPoints.length;

  const province = storage.netSelectProvince,
    city = storage.netSelectCity,
    date = storage.netSelectDate;

  const paramObj = {
    stage: stage,
    strokeStyle: 'rgb(136, 123, 39)',
    anticlock: true,
    event: 'click',
    cellInfoUrl: requestUrl.cellInfo,
    cellInfoRequestData: {
      date: date
    },
    map: map,

    chartLine: chart.line,
    chartLineUrl: requestUrl.cellDataByMonth,
    chartLineRequestData: {
      date: date
    },
    loadDetailUrl: requestUrl.loadDetail,
    loadDetailRequestData: {
      date: date,
      province: province,
      city: city
    },
    // allPoorPoints: allPoorPoints,
    // $chartLine: $('#chart_line'),
    // mainHeight: gData.mainHeight
  };

  // 质差小区
  if ($('.top-bar__tab.active')[0].id === 'poor_ana' && allPoorLength > 0) {
    for (let i = 0; i < allPoorLength; i++) {
      if (info.bounds.contains([allPoorPoints[i].y, allPoorPoints[i].x])) {
        const dot = map.latLngToContainerPoint([allPoorPoints[i].y, allPoorPoints[i].x]);

        const sectors = allPoorPoints[i].cl,
          sectorLength = sectors.length;

        let circleFillStyle = 'rgb(210, 210, 210)',
          circleRadius = 4;

        if (allPoorPoints[i].hi === true) {
          circleFillStyle = 'purple';
        }

        for (let j = 0; j < sectorLength; j++) {
          const sector = sectors[j];

          let radius = 20;

          if (sector.hi === true) {
            radius = 36;
          }

          paramObj.fillStyle = gMap.poorFillStyle[sector.ty];
          paramObj.radius = radius;
          paramObj.x = dot.x;
          paramObj.y = dot.y;
          paramObj.start = -(450 - sector.an - 20);
          paramObj.end = -(450 - sector.an + 20);

          paramObj.cellInfoRequestData = {
            date: date,
            id: sector.cid,
            type: sector.ty
          };

          paramObj.chartLineRequestData.id = sector.cid;
          paramObj.loadDetailRequestData.id = sector.cid;

          Draw.sector(paramObj);
        }

        Draw.sector({
          stage: stage,
          x: dot.x,
          y: dot.y,
          start: 0,
          end: 360,
          radius: circleRadius,
          fillStyle: circleFillStyle,
          // fillStyle: 'yellow',
          strokeStyle: 'rgb(136, 123, 39)',
          anticlock: true,
          event: undefined,
          // requestData: {
          //     cellId: allPoorPoints[i].id,
          //     taskId: Page.getTaskId(),
          //     date: Page.getDate(),
          //     taskType: Page.getType()
          // },
          // info: {
          //     type: 'sector',
          //     angle: sectors
          // },
          // map: map,
          // poorPoints: allPoorPoints,
        });
      }
    }

    if (gData.commonChk === true) {
      const commonPoints = gData.commonCellList,
        commonLength = commonPoints.length;

      for (let i = 0; i < commonLength; i++) {
        if (info.bounds.contains([commonPoints[i].y, commonPoints[i].x])) {
          const dot = map.latLngToContainerPoint([commonPoints[i].y, commonPoints[i].x]);
          const sectors = commonPoints[i].cl,
            sectorLength = sectors.length;

          for (let j = 0; j < sectorLength; j++) {
            Draw.sector({
              stage: stage,
              x: dot.x,
              y: dot.y,
              start: -(450 - sectors[j].an - 20),
              end: -(450 - sectors[j].an + 20),
              radius: 20,
              fillStyle: 'rgba(209, 203, 177, 0.2)',
              strokeStyle: 'rgb(136, 123, 39)',
              anticlock: true,
              event: undefined,
            });
          }

          Draw.sector({
            stage: stage,
            x: dot.x,
            y: dot.y,
            start: 0,
            end: 360,
            radius: 4,
            fillStyle: 'rgb(210, 210, 210)',
            strokeStyle: 'rgb(136, 123, 39)',
            anticlock: true,
            event: undefined,
          });
        }
      }
    }
  } else if ($('.top-bar__tab.active')[0].id === 'expand_plan') {
    const addPoints = (gData.addCell === undefined) ? [] : gData.addCell,
      addLength = addPoints.length;

    for (let i = 0; i < addLength; i++) {
      if (info.bounds.contains([addPoints[i].y, addPoints[i].x])) {
        const dot = map.latLngToContainerPoint([addPoints[i].y, addPoints[i].x]);
        const sectors = addPoints[i].cl,
          sectorLength = sectors.length;

        sectors.sort(function (a, b) {
          const freqA = a.freq.toUpperCase(),
            freqB = b.freq.toUpperCase();

          if (freqA < freqB) {
            return -1;
          }

          if (freqA > freqB) {
            return 1;
          }

          return 0;
        });

        for (let j = 0; j < sectorLength; j++) {

          const an = sectors[j].an,
            freq = sectors[j].freq;

          const radiusMap = {
            D1: 34,
            D2: 28,
            D3: 24,
            F1: 20,
            F2: 16
          };

          const fillStyleMap = {
            D1: 'rgb(107, 57, 6)',
            D2: 'rgb(152, 36, 207)',
            E1: 'yellow',
            E2: 'green',
            E3: 'blue',
            D3: 'rgb(235, 97, 0)',
            F1: 'rgb(234, 96, 155)',
            F2: 'rgb(254, 12, 63)'
          };

          switch (freq) {
            case 'D1':
            case 'D2':
            case 'D3':
            case 'F1':
            case 'F2':
              Draw.sector({
                stage: stage,
                x: dot.x,
                y: dot.y,
                start: SectorAngle.start(an, 20),
                end: SectorAngle.end(an, 20),
                // radius: 20,
                radius: radiusMap[freq],
                // fillStyle: 'red',
                fillStyle: fillStyleMap[freq],
                strokeStyle: 'rgb(136, 123, 39)',
                anticlock: true,
                event: undefined,
                // addCellInfo: sectors
                // requestData: {
                //     cellId: poorPoints[i].id,
                //     taskId: Page.getTaskId(),
                //     date: Page.getDate(),
                //     taskType: Page.getType()
                // },
                // info: {
                //     type: 'sector',
                //     angle: sectors
                // },
                // map: map,
                // poorPoints: poorPoints,
              });
              break;
            case 'E1':
            case 'E2':
            case 'E3':
              Draw.sector({
                stage: stage,
                x: dot.x,
                y: dot.y,
                start: 0,
                end: 360,
                // radius: 20,
                radius: 4,
                // fillStyle: 'red',
                fillStyle: fillStyleMap[freq],
                strokeStyle: 'rgb(136, 123, 39)',
                anticlock: true,
                event: undefined,
                // addCellInfo: sectors
                // requestData: {
                //     cellId: poorPoints[i].id,
                //     taskId: Page.getTaskId(),
                //     date: Page.getDate(),
                //     taskType: Page.getType()
                // },
                // info: {
                //     type: 'sector',
                //     angle: sectors
                // },
                // map: map,
                // poorPoints: poorPoints,
              });

              break;
            default:
          }

        }

      }
    }
  }

  stage.update();
}